/*
 * $URL: http://dnsprobe.googlecode.com/svn/trunk/dnsprobe/src/dnsprobe/controller/ControllerMain.java $
 * 
 * Copyright (c) 2009, Anonymous
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Anonymous nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY ANONYMOUS ''AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL ANONYMOUS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */

package dnsprobe.controller;


import static dnsprobe.Constants.COMMAND_CHANGE_CUSTOM_NAMESERVER;
import static dnsprobe.Constants.COMMAND_CHANGE_NAMESERVER;
import static dnsprobe.Constants.COMMAND_LOAD_HOSTLIST;
import static dnsprobe.Constants.COMMAND_SAVE_EXPORT;
import static dnsprobe.Constants.COMMAND_START_RESOLVE;
import static dnsprobe.Constants.COMMAND_STOP_RESOLVE;
import static dnsprobe.Constants.EXPORT_FILENAME;
import static dnsprobe.Constants.MSG_EXPORT_FAILED;
import static dnsprobe.Constants.MSG_EXPORT_NODATA;
import static dnsprobe.Constants.MSG_EXPORT_SUCCESSFUL;
import static dnsprobe.Constants.MSG_IMPORT_LOADED;
import static dnsprobe.Constants.MSG_RESOLVE_DONE;
import static dnsprobe.Constants.MSG_RESOLVE_DURATION;
import static dnsprobe.Constants.MSG_RESOLVE_ERROR_GENERAL;
import static dnsprobe.Constants.MSG_RESOLVE_ERROR_UNKNOWN_HOST;
import static dnsprobe.Constants.MSG_RESOLVE_START;
import static dnsprobe.Constants.MSG_IMPORT_NOT_LOADED;
import static dnsprobe.Constants.MSG_IMPORT_NOT_FOUND;
import static dnsprobe.Constants.DEFAULT_PROVIDER_OPEN;
import static dnsprobe.Constants.RESOLVER_CFG_MAX_THREADS;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.SwingUtilities;

import dnsprobe.data.AccessProvider;
import dnsprobe.data.ApplicationData;
import dnsprobe.data.Hostname;
import dnsprobe.data.Statistics;
import dnsprobe.gui.View;
import dnsprobe.io.FileHandler;
import dnsprobe.resolver.Nameserver;
import dnsprobe.resolver.ResolverTask;

/**
 * ActionListener fuer die GUI
 * 
 * @author BerndBernhardson
 * @author anon004
 * @author snoop
 * @version $Id: ControllerMain.java 164 2009-07-08 01:42:55Z bernhardson@gmx.net $
 *
 */
public class ControllerMain implements Controller.Main
{
	/**
	 * Thread-Pool
	 */
	private ExecutorService workerPool;
	
	/**
	 * Referenz auf Das ApplicationData Objekt
	 */
	private ApplicationData model;
	
	/**
	 * Referenz auf das GUI-Objekt
	 */
	private View.Main view;
	
	
	/**
	 * Konstruktor
	 */
	public ControllerMain()
	{
		workerPool = Executors.newFixedThreadPool(RESOLVER_CFG_MAX_THREADS);
	}
	
	/**
	 * setzt das Model fuer den Controller
	 * 
	 * @param model Das Model fuer den Controller
	 */
	public void setModel(final ApplicationData model)
	{
		this.model = model;
	}
	
	/**
	 * setzt die View fuer den Controller
	 * 
	 * @param view Die View fuer den Controller
	 */
	public void setView(final View.Main view)
	{
		this.view = view;
	}
	
	/**
	 * Dispatcher fuer die Aktionen
	 */
	@Override
	public void actionPerformed(final ActionEvent e) 
	{
		// lookup starten
		if(COMMAND_START_RESOLVE.equals(e.getActionCommand()))
		{
			startResolver();
		}
		
		// lookup anhalten
		if(COMMAND_STOP_RESOLVE.equals(e.getActionCommand()))
		{
			stopResolver();
		}
		
		// host-datei laden
		if(COMMAND_LOAD_HOSTLIST.equals(e.getActionCommand()))
		{
			loadHostList();
		}
		
		// ergebnis exportieren
		if(COMMAND_SAVE_EXPORT.equals(e.getActionCommand()))
		{
			exportResult();
		}
		
		// nameserver aktualisieren
		if(COMMAND_CHANGE_NAMESERVER.equals(e.getActionCommand()))
		{
			changeNameserver();
		}
		
		// own dns aendern
		if(COMMAND_CHANGE_CUSTOM_NAMESERVER.equals(e.getActionCommand()))
		{
			changeNameserverAddress();
		}
	}

	/**
	 * Sendet eine Log-Meldung an die GUI
	 * 
	 * TODO PropertyChangeListener implementieren
	 * 
	 * @param parts Die Teile der Textzeile
	 */
	public synchronized void printLog(final Object... parts)
	{
		// EDT soll nicht blockieren
		SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				view.printLog(parts);
			}
		});
	}
	
	/**
	 * wird ausgefuehrt wenn ein task fertig ist
	 * 
	 * TODO PropertyChangeListener implementieren
	 */
	public synchronized void taskDone()
	{
		if(model.getStatistics().isDone())
		{
			model.getStatistics().resolvingStopped();
		}
		
		// EDT soll nicht blockieren
		SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				view.updateIpTableModel();
				view.updateStatistics();
				
				if(model.getStatistics().isDone())
				{
					view.printLog(MSG_RESOLVE_DONE);
					view.printLog(MSG_RESOLVE_DURATION, model.getStatistics().getDurationAsString());
				}
			}
		});
	}

	/**
	 * Startet den Resolver
	 */
	private void startResolver()
	{
		final Statistics     statistics;
		final List<Hostname> hostnames;
		final AccessProvider currentProvider;
	
		statistics      = model.getStatistics();
		hostnames       = model.getHostnameList();
		currentProvider = model.getCurrentAccessProvider();
		
		statistics.reset(hostnames.size() * 2, hostnames.size());
		
		try
		{
			final Nameserver openNameserver;
			final Nameserver userNameserver;
			
			openNameserver = Nameserver.newNameserver(DEFAULT_PROVIDER_OPEN);
			userNameserver = Nameserver.newNameserver(currentProvider);
		
			printLog(MSG_RESOLVE_START);
			
			statistics.resolvingStarted();
			
			for(final Hostname hostname : hostnames)
			{
				try
				{
					workerPool.execute(new ResolverTask(hostname, openNameserver, userNameserver));
				}
				catch(final Exception e)
				{
					printLog(MSG_RESOLVE_ERROR_GENERAL);
					e.printStackTrace();
				}
			}
		}
		catch(UnknownHostException e)
		{
			view.printLog(MSG_RESOLVE_ERROR_UNKNOWN_HOST);
		}
	}

	/**
	 * Stoppt den Resolver
	 */
	private void stopResolver()
	{
		workerPool.shutdown();
	}
	
	/**
	 * Laedt eine neue Host-Datei
	 */
	private void loadHostList()
	{
		final File file;
		
		file = view.chooseInputFile();
		
		if(file == null)
		{
			return;
		}
		
		try
		{
			final List<Hostname> newHostList;
			
			newHostList = FileHandler.readHostListFromFile(file);
			
			// alte daten verwerfen
			if(newHostList.size() > 0)
			{
				model.getStatistics().reset();
				
				model.getHostnameList().clear();
				model.getHostnameList().addAll(newHostList);
				
				view.updateImportPath(file.getPath());
				view.updateStatistics();
				view.updateIpTableModel();
				
				view.clearLog();
				view.printLog(MSG_IMPORT_LOADED, file.getPath());
			}
		}
		catch(FileNotFoundException e)
		{
			view.printLog(MSG_IMPORT_NOT_FOUND);
		}
		catch(IOException e)
		{
			view.printLog(MSG_IMPORT_NOT_LOADED);
		}
	}
	
	/**
	 * Exportiert die aktuelle Ergebnis-Liste
	 */
	private void exportResult()
	{
		if(model.getHostnameList().size() == 0)
		{
			view.printLog(MSG_EXPORT_NODATA);
			return;
		}
		
		final File file;
		
		file = view.chooseOutputFile(new File(EXPORT_FILENAME));
		
		if(file == null)
		{
			return;
		}
		
		try
		{
			FileHandler.writeHostListToFile
			(
				file,
				model.getHostnameList(), 
				model.getCurrentAccessProvider(),
				view.getSelectedExportType()
			);
		}
		catch(IOException ex)
		{
			view.printLog(MSG_EXPORT_FAILED);
			return;
		}
		
		view.printLog(MSG_EXPORT_SUCCESSFUL);
	}
	
	/**
	 * Aendert den aktuellen Nameserver
	 */
	private void changeNameserver()
	{
		try
		{
			final AccessProvider accessProvider;
			
			accessProvider = view.getSelectedAccessProvider();
			
			InetAddress.getByName(accessProvider.getAddress());
			
			model.setCurrentAccessProvider(accessProvider);
			view.setAccessProviderAddress(accessProvider);
		}
		catch(UnknownHostException e)
		{
			view.printLog(MSG_RESOLVE_ERROR_UNKNOWN_HOST);
		}
	}

	/**
	 * Aendert die Adresse des aktuellen Nameservers
	 */
	private void changeNameserverAddress()
	{
		try
		{
			final String address;
			
			address = InetAddress.getByName(view.getAccessProviderAddess()).getHostAddress();
			
			if(model.getCurrentAccessProvider() != null)
			{
				model.getCurrentAccessProvider().setAddress(address);
			}
		}
		catch(UnknownHostException e)
		{
			view.printLog(MSG_RESOLVE_ERROR_UNKNOWN_HOST);
		}
	}
}
